package ke04;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;

public class SwingWorkerDemo extends JFrame {

	private JProgressBar bar;
	private JButton load;

	public SwingWorkerDemo() {
		setDefaultCloseOperation(EXIT_ON_CLOSE);

		bar = new JProgressBar(0, 100);
		bar.setPreferredSize(new Dimension(400, 50));

		load = new JButton("Load!");
		load.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
			
				load.setEnabled(false);
				bar.setString("Loading...");
				bar.setStringPainted(true);
				
				new SwingWorker<Void,Integer>(){

					@Override
					protected Void doInBackground() throws Exception {
						for (int i = 0; i <= 100; i++) {
							try {
								Thread.sleep((long) (Math.random() * 150));
							} catch (InterruptedException e1) {
								e1.printStackTrace();
							}
							publish(i);
						}
						return null;
					}
					
					protected void process(java.util.List<Integer> chunks)
					{
						int perc = chunks.get(chunks.size()-1);
						bar.setValue(perc);
						bar.setString("Loading... " + perc + "%");
					};
					
					protected void done() {
						bar.setValue(0);
						bar.setStringPainted(false);
						load.setEnabled(true);
					};
					
				}.execute();
			}
		});

		getContentPane().setLayout(new BorderLayout());
		getContentPane().add(load, BorderLayout.NORTH);
		getContentPane().add(bar, BorderLayout.CENTER);
		pack();
	}

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				JFrame f = new SwingWorkerDemo();
				f.setLocationRelativeTo(null);
				f.setVisible(true);
			}
		});
	}
}

